package javax.per.toolkit.sys;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ClipboardUtil {
	
	private static Clipboard clipboard=Toolkit.getDefaultToolkit().getSystemClipboard();
	
	public static String getText(){
		Transferable t=clipboard.getContents(null);
		if(t!=null&&t.isDataFlavorSupported(DataFlavor.stringFlavor)){
			try {
				return (String)t.getTransferData(DataFlavor.stringFlavor);
			} catch (UnsupportedFlavorException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "";
	}
	
	public static void setText(String text){
		StringSelection strsel=new StringSelection(text);
		clipboard.setContents(strsel, null);
	}
	
	public static List<File> getFiles(){
		Transferable t=clipboard.getContents(null);
		if(t!=null){
			if(t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)){
				try {
					@SuppressWarnings("unchecked")
					List<File> files=(List<File>)t.getTransferData(DataFlavor.javaFileListFlavor);
					return files;
				} catch (UnsupportedFlavorException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
	
	public static void setFile(String path){
		File file=new File(path);
		List<File> files=new ArrayList<File>();
		files.add(file);
		setFiles(files);
	}
	
	public static void setFiles(List<File> files){
		FileListSelection fl=new FileListSelection(files);
		clipboard.setContents(fl, null);
	}
	
	
	
	private static  class FileListSelection implements Transferable{
		
		private List<File> fileList;
		
		public FileListSelection(List<File> files){
			this.fileList=files;
		}

		@Override
		public DataFlavor[] getTransferDataFlavors() {
			return new DataFlavor[]{DataFlavor.javaFileListFlavor};
		}

		@Override
		public boolean isDataFlavorSupported(DataFlavor flavor) {
			return DataFlavor.javaFileListFlavor.equals(flavor);
		}

		@Override
		public Object getTransferData(DataFlavor flavor)
				throws UnsupportedFlavorException, IOException {
			if(!DataFlavor.javaFileListFlavor.equals(flavor))
				throw new UnsupportedFlavorException(flavor);
			return fileList;
		}
		
	}
	
}


